package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 1-87-1 商品服务-API-新增商品-商品新增业务流程分析
     * 保存的思路流程, 见注释
     * <p>
     * 1-88-1 商品服务-API-新增商品-保存SPU基本信息
     * <p>
     * 1-89-1 商品服务-API-新增商品-保存SKU基本信息
     * <p>
     * 1-90-1 商品服务-API-新增商品-调用远程服务保存优惠等信息
     * 涉及coupon服务的
     * <p>
     * 1-92-1 商品服务-API-新增商品-商品保存其他问题处理
     * <p>
     * TODO 高级部分待完善
     *
     * @param vo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1 保存spu的基本信息SpuSaveVo（pms_spu_info）
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(vo, spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2 保存它的描述decript（pms_spu_info_desc）
        List<String> decriptEntity = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setDecript(String.join(",", decriptEntity));
        // 这里要设置主键的id为自己输入, 不是默认的自增
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //操作什么实体类就调用它对应的方法实现
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 3 保存它的图片集images（pms_spu_images）
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 4 保存spu的规格参数baseAttrs（pms_product_attr_value）
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());
            //调用attrService里面的方法实时找到属性名
            AttrEntity attrEntityById = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntityById.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBaseAttrs(collect);

        // 5 保存spu的积分信息bounds   mall-coupon-》sms_spu_bounds
        // 调用远程服务
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 6 保存当前spu对应的所有sku信息skus
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            // 由于sku众多, 需要遍历
            skus.forEach(item -> {
                String defaultImg = "";
                // 获取默认图片
                for (Images images1 : item.getImages()) {
                    if (images1.getDefaultImg() == 1) {
                        defaultImg = images1.getImgUrl();
                    }
                }
                // 6.1 sku的基本信息：（pms_sku_info）
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                // 只有这四个属性vo和entity是一样的
                //private String skuName;
                //private BigDecimal price;
                //private String skuTitle;
                //private String skuSubtitle;
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                // 保存了sku之后sku的主键有了
                Long skuId = skuInfoEntity.getSkuId();

                // 6.2 sku的图片信息 images（pms_sku_images）
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
//                    skuImagesEntity.setImgSort(1);
                    return skuImagesEntity;
                }).filter(entity ->
                        // 1-92-1 商品服务-API-新增商品-商品保存其他问题处理
                        // 过滤图片路径为空的, 返回true就是需要, false就是剔除
                        StringUtils.isEmpty(entity.getImgUrl())
                ).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                // TODO 没有图片; 路径的无须保存

                // 6.3 sku的销售属性  attr （pms_sku_sale_attr_value）
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(attrs -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attrs, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 6.4 sku的优惠，满减等信息 mall-coupon-》
                // sms_sku_ladder打折表，sms_sku_full_reduction满减表，sms_member_price会员价格
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 1-92-1 商品服务-API-新增商品-商品保存其他问题处理
                // 打折数量或者满减金额不为零时才调用远程服务
                if (skuReductionTo.getFullCount() > 0 ||
                        skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }
    }

    /**
     * 1-88-1 商品服务-API-新增商品-保存SPU基本信息
     * 保存spu的基本信息SpuSaveVo（pms_spu_info）
     *
     * @param spuInfoEntity
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * 1-93-1 商品服务-API-商品管理-SPU检索
     * 做改造, 能够通过条件查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            // queryWrapper.and代表如下意思
            // status=1 and catalog_id = 1 and (id=1 or spu_name like xxx)
            // 相当于内嵌查询条件
            queryWrapper.and(w-> w.eq("id",key).or().like("spu_name",key));
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);

        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);

        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){

            queryWrapper.eq("publish_status",status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),queryWrapper
        );

        return new PageUtils(page);
    }

}